/**
 * 共有逻辑的处理与接口
 */

var testOnly = false;

// 本游戏的最大注单数
var _maxBetCount = 0;
function checkBetCount(count) {
    // 注单数没有限制
    if (_maxBetCount == 0) return true;
    var curr = Lottery.totalCount(Lottery.curr());
    if (curr + count <= _maxBetCount) return true;

    var t = Math.max(0, _maxBetCount - curr);
    alert2("下注单数超过上限，投注失败！<br/>当前还可以下注：" + t + "注！", true);
    return false;
}

/**
 * 初始化游戏页面
 */
function initGame(game, cb, useNumber) {
    $(".menu .open_result").attr("href", switchCenter("开奖结果", get_game_display_name(game)));
    $(".menu .game_rule").attr("href", switchCenter("游戏规则", get_game_display_name(game))); 
    $(".menu a.wjmx").attr("href", switchCenter("我的投注", "未结明细"));
    $(".menu a.today").attr("href", switchCenter("我的投注", "今日已结"));
    $("#left a.charge").attr("href", switchCenter("资金管理", "我要充值"));
    $("#left a.take").attr("href", switchCenter("资金管理", "我要取款"));

    Classify.query("bet.count", game, false, '0', function(v) {
        _maxBetCount = parseInt(v);
    });

    // 公告
    Notice.loop();

    // 开奖结果
    Result.switchGame(game);
    Result.cb = function() {
        // 开奖提醒
        var c = Result.last();
        if (c)
            set_lastest_result(c.issue, c.red, useNumber);
        else
            set_lastest_result();

        // 倒计时
        c = Result.curr();
        if (c) {
            var open = c.open / 1000 || 0,
                end = c.end / 1000 || 0;
            context.curr[game] = c.issue;
            set_countdown(parseInt(open - get_server_time()), parseInt(end - get_server_time()), c.issue, c.betEnable);
        }
    };
    Result.refreshListCb = function() {
        // 更新长龙
        var list = gameRule.long(context.result[game]);
        set_long_queue(list);
    };

    // 投注记录
    Lottery.switchGame(game);
    Lottery.cb = function() {
        var lottery = context.lottery[game];
        if (!isEmpty(lottery)) {
            // 填充进来
            var map = gameRule.map;
            for (var k in lottery) {
                if (isEmpty(map[k])) {
                    console.log("不存在的类型", k);
                    continue;
                }
                map[k].rate = lottery[k].value;
            }
        }
        refresh_bet_items();

        // 填充下注列表
        refresh_curr_bet_list();

        // 计算本游戏未结算总金额
        var r = query_all_uncheck_bets()[game];
        $(".weijie .red").html("(" + (isEmpty(r) ? 0 : (r.bet/100).toFixed(2)) + ")");
    };
    
    // 填入筹码输入框
    scan_counter_confirm();

    // 回调填充内容
    cb();
    scan_bet_items();

    // 账号信息改变的回调
    ME.cb = function() {
        set_account_info(ME.get_name(), ME.balance(), ME.pending());
        Result.todayProfit(function(r) {
            var arr = $(".today_win");
            ////----arr.html("(" + (r.amount/100).toFixed(2) + ")");
            arr.html("(--)");
        });
    };
    ME.cb();

    // 定期抓取赢的数据
    setInterval(function() {
        Result.bet_win_query();
    }, 5 * 1000);
}

/**
 * 当前是否可以下注
 */
function can_bet() {
    var c = Result.curr();
    if (!c || !isEmpty(c.red)) return false;
    if (c.end/1000 - get_server_time() <= 0) return false;
    return true;
}

/**
 * 填充投注项的分页信息
 */
function fill_tabs(arr) {
    var div = $(".menu-left");
    div.empty();
    var template = '<a href="#" value="__v__" class="__c__">__n__</a>';
    for (var i = 1; i <= arr.length; i++) {
        var l = template.replace(/__v__/, i);
        l = l.replace(/__n__/, arr[i - 1]);
        l = l.replace(/__c__/, i == 1 ? 'active' : '');
        div.append(l);
    }

    // 关注点击事件
    var arr = $("#game .page");
    $(".menu-left a").click(function(e) {
        var t = $(e.currentTarget);
        if (t.attr("class") == 'active') return;

        $(".menu-left a").attr("class", '');
        t.attr("class", 'active');
        var index = parseInt(t.attr("value"));
       
        arr.hide();
        $(arr[index - 1]).show();

        // 切换分页后，需要重置下投注信息
        reset_counter();
    });

    arr.hide();
    $(arr[0]).show();
}

/**
 * 取得当前显示的分页信息
 */
function get_show_tab() {
    for (var i = 1; i < 30; i++) {
        var p = $(".page" + i);
        if (p.css("display") != 'none') {
            return i;
        }
    }
}

/**
 * 设置最近一期的开奖结果
 * name为第几期, list为结果列表，例如：
 * set_lastest_result("165230", [3, 3, 2, 1, 5, 6, 7, 8, 9, 10])
 */
function set_lastest_result(name, list, useNumber) {
    if (name)
        $(".result2 .issue").html(name + "期");
    else
        $(".result2 .issue").html("--期");
    var r = $(".result2 .result");
    r.html("");

    if (list && window.parseLastestResult)
        list = parseLastestResult(list);

    if (list) {
        for (var i in list) {
            if (window.customDrawResult)
                // 使用自定义的绘制方法
                var line = '<div class="item item__index__">' + window.customDrawResult(list[i]) + '</div>';    
            else if (!useNumber)
                var line = '<div class="item item__index__"><img src="images/__i__.png" /></div>';
            else {
                var line = '<div class="item item__index__">__i__</div>';
            }
                
            if (i == list.length - 1)
                line = line.replace(/__index__/, parseInt(list[i]) + " item_last");
            else
                line = line.replace(/__index__/, parseInt(list[i]));
            line = line.replace(/__i__/, list[i]);
            r.append(line);

            if (i == 9) {
                // 最多显示10个一行
                r.append('<div class="clear"></div>');
            }
        }
    }
    
    r.append('<div class="clear"></div>');

    // 绘制其他的信息
    if (window.lastest_result2) {
        list = lastest_result2();
        if (!list) return;

        for (var i in list) {
            var line = '<div class="item_row2">' + list[i] + '</div>';
            r.append(line);
        }
    }
}

/**
 * 开启倒计时，单位为秒
 * 分别为开奖倒计时和封盘倒计时
 */
function set_countdown(openTime, closeTime, issue, betEnable) {
    betEnable = betEnable === undefined ? true : betEnable;
    if (timer)  {
        clearTimeout(timer);
        timer = 0;
    }
    if (!issue) {
        $(".fengpan .issue").html("--期");
        $(".fengpan .kj .kj").html("00:00");
        $(".fengpan .fp .fp").html("00:00");
        on_fengpan();
        return;
    }

    start = new Date().getTime()/1000;
    var f = function() {
        var delta = new Date().getTime()/1000 - start;
        var t = openTime - delta;
        if (t < 0) t = 0;
        if (t >= 3600) {
            // 超过1小时
            $(".fengpan .kj .kj").html(Math.floor(t/3600) + '小时');
        }
        else {
            var i1 = parseInt(t / 60), i2 = Math.ceil(t % 60);
            $(".fengpan .kj .kj").html((i1 < 10 ? "0" + i1 : i1) + ":" + (i2 < 10 ? "0" + i2 : i2));
        }

        t = closeTime - delta;
        if (t < 0) t = 0;
        if (t >= 3600) {
            // 超过1小时
            $(".fengpan .fp .fp").html(Math.floor(t/3600) + '小时');
        }
        else {
            i1 = parseInt(t / 60), i2 = Math.ceil(t % 60);
            $(".fengpan .fp .fp").html((i1 < 10 ? "0" + i1 : i1) + ":" + (i2 < 10 ? "0" + i2 : i2));
        }

        if (t == 0 || !betEnable) on_fengpan();
        else on_kaipan();
    };
    f();
    timer = setInterval(f, 200);

    // 第几期
    $(".fengpan .issue").html(issue + "期")
}
var timer, start;

/**
 * 设置账户信息，参数分别为：账号名称、余额、未结算金额
 * 如果传递undefined，则表示没有变化
 */
function set_account_info(name, money, betMoney) {
    if (name !== undefined)
        $(".account .name").html(name);
    if (betMoney !== undefined)
        $(".account .bet_money").html(betMoney/100 + "");
    $(".balance").html((money/100).toFixed(2));
}

/**
 * 设置长龙的信息，参数list为数组，如
 * [
 *     { name: '冠亚大', value: 6 },
 *     ...
 * ]
 */
function set_long_queue(list) {
    var table = $(".long tbody");
    table.empty();
    for (var i in list) {
        var o = list[i];
        var k, v;
        for (var j in o) {
            k = j;
            v = o[j];
        }
        var tr = $("<tr></tr>");

        tr.append("<td>" + k + "</td>");
        tr.append("<td class='qi' style='width:60px;text-align:center;'>" + v + "期</td>");
        table.append(tr);
    }
}

/**
 * 设置投注的历史信息，参数list为数组，如：
 * [{ name: "冠军 大", odds: 1.99, total: 2000  }, ...]
 * 
 */
function set_bet_history(list) {
    var total = 0;
    var table = $(".bet_history tbody");
    table.empty();
    for (var i in list) {
        var o = list[i];
        var tr = $("<tr></tr>");

        tr.append("<td class='name'>" + o.name + "</td>");
        tr.append("<td class='odds'>" + o.odds + "</td>");
        tr.append("<td class='total'>" + o.total/100 + "</td>");
        table.append(tr);
        total += parseInt(o.total);
    }

    $(".total_bet").html("总金额：<span>" + total/100 + '</span>');
}

/**
 * 跳转到个人中心
 */
function switchCenter(n1, n2, params) {
    var url = context.config.center + "?n1=";
    if (n1) url += n1;
    if (n2) url += "&n2=" + n2;
    if (Util.sid && testOnly) url += "&sid=" + Util.sid;
    if (params) {
        for (var k in params) {
            url += "&" + k + "=" + params[k];
        }
    }
    return encodeURI(url);
}

// 刷新本期投注信息
function refresh_curr_bet_list() {
    var bets = context.bets[game] || {};
    var issue = Lottery.curr() || "";
    bets = bets[issue] || [];

    // 对同一组的信息做下合并
    var data = Lottery.combineGroup(bets);

    var list = [];
    for (var k in data) {
        var o = data[k];
        if (o.group) {
            k = o.group.split("_")[0];
        }
        else k = gameRule.getTargetName(o.target);

        list.push({
            name: k,
            odds: o.rate,
            total: o.amount
        });
    }
    set_bet_history(list);
}

// 表单验证的逻辑


// 显示某期的盈利结果
function show_profit_view(type, issue, result) {
    $("#popup .title img").attr("src", "images/title-result.png");
    Lottery.today(function(r) {
        switch_page("profit", $('#popup_content'), function() {
            // 填充数据
            $(".profit-view .issue").html(issue + "期");
            $(".profit-view .total").html(result.amount/100);
            $(".profit-view .profit").html(result.profit/100);
        });
        $("#popup").modal({
            width:1024,
        });
    });
}

/**
 * 获取即时注单的信息
 */
function query_all_uncheck_bets() {
    var bets = context.bets;
    var games = get_game_list();
    var r = {};
    for (var i in games) {
        var g = games[i];
        r[g] = {
            count: 0,
            bet: 0,
        };

        var bet = bets[g];
        if (isEmpty(bet)) continue;
        for (var k in bet) {
            for (var j in bet[k]) {
                var o = bet[k][j];
                if (o.state != 0) continue;
                r[g].count++;
                r[g].bet += o.amount;
            }
        }
    }
    return r;
}
